package com.rachel.apkupdate;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.rachel.apkupdate.ToolUtils.log;
import com.rachel.apkupdate.entris.FileInfo;
import com.rachel.apkupdate.entris.LocalInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhengshaorui on 2017/4/13.
 */

public class CheckVersionManager {
    private static final String TAG = "zsr";
    private static final String NETWORK_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
    private static final String JSONURL = "http://upgrade.toptech-developer.com/file/floatball/floatballupdate.json";
    public static final int SHOW_UPDATE_WINDOW_MSG = 1;
    private Context mContext;

    Handler mHandler = new Handler(Looper.getMainLooper());

    private VersionCallback mCallback;

    private CheckVersionManager(Context context,VersionCallback callback){
        init(context);
        mCallback = callback;
    };
    private volatile  static CheckVersionManager manager;
    public static CheckVersionManager getInstance(Context context,VersionCallback callback){
        if (manager == null){
            synchronized (CheckVersionManager.class){
                if (manager == null){
                    manager = new CheckVersionManager(context,callback);
                }
            }
        }
        return manager;
    }

    public void init(Context context){
        mContext = context;

        IntentFilter filter = new IntentFilter();
        filter.addAction(NETWORK_CHANGE);
        mContext.registerReceiver(NetUpdateReceiver,filter);

    }

    private int getFileSize(String url){
        StringBuffer sb = null;
        HttpURLConnection connection =null;
        try {
            URL httpurl = new URL(url);
            connection = (HttpURLConnection) httpurl.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            int filesize = connection.getContentLength();
            return filesize;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (connection != null){
                connection.disconnect();
            }
        }
        return 0;
    }
    /**
     * 从服务器获取更新信息
     * @param url
     * @return
     */
    private String getJsonFromUrl(String url){
        StringBuffer sb = null;
        HttpURLConnection connection =null;
        try {
            URL httpurl = new URL(url);
            connection = (HttpURLConnection) httpurl.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(20000);
            connection.setConnectTimeout(20000);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(),"utf-8"));
            sb = new StringBuffer();
            String line = null;
            while( (line = br.readLine())!= null ){
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.d("getjson: "+e.toString());
        }finally {
            if (connection != null){
                connection.disconnect();
            }
        }
        if (sb == null){
            return null;
        }
        return sb.toString();
    }

    BroadcastReceiver NetUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive: "+action);
            ConnectivityManager connectivityManager = (ConnectivityManager)
                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean isWifiC = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            boolean isETHERNETC = false;
            try { //这个有线连接为了兼容linux平台
                isETHERNETC = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).isConnected();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (isETHERNETC || isWifiC){
                new Thread(new Runnable() {
                   

                    @Override
                    public void run() {
                        String jsondata = getJsonFromUrl(JSONURL);
                        if (jsondata != null) {
                            try {
                                JSONObject Root = new JSONObject(jsondata);
                                final FileInfo apkInfo = new FileInfo();
                                apkInfo.setFilename("floatball"+".apk");
                                apkInfo.setVersioncode(Root.getInt("versioncode"));
                                apkInfo.setVersionname(Root.getString("versionname"));
                                apkInfo.setVersionmsg(Root.getString("versionmsg"));
                               // apkInfo.setFileurl(Root.getString("apkurl"));
                                apkInfo.setFileurl("http://downloads.jianshu.io/apps/haruki/jianShu-release-2.1.3-JianShu.apk");
                                apkInfo.setFilesize(getFileSize(apkInfo.getFileurl()));


                                Log.d(TAG, "apk: " + apkInfo);
                                LocalInfo localInfo = getLocalInfo(mContext);
                                if (localInfo.getVersioncode() < apkInfo.getVersioncode()){
                                   // Toast.makeText(mContext, "可以更新", Toast.LENGTH_SHORT).show();
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            mCallback.update(apkInfo);
                                        }
                                    });

                                }else{
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            mCallback.lastest();
                                        }
                                    });

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.d(TAG, "eroor: " + e.toString());
                            }
                        }
                    }
                }).start();
            }
        }
    };

    public void test(){
        new Thread(new Runnable() {


            @Override
            public void run() {
                String jsondata = getJsonFromUrl(JSONURL);
                if (jsondata != null) {
                    try {
                        JSONObject Root = new JSONObject(jsondata);
                        final FileInfo apkInfo = new FileInfo();
                        apkInfo.setFilename("floatball"+".apk");
                        apkInfo.setVersioncode(Root.getInt("versioncode"));
                        apkInfo.setVersionname(Root.getString("versionname"));
                        apkInfo.setVersionmsg(Root.getString("versionmsg"));
                        // apkInfo.setFileurl(Root.getString("apkurl"));
                        apkInfo.setFileurl("http://downloads.jianshu.io/apps/haruki/jianShu-release-2.1.3-JianShu.apk");
                        apkInfo.setFilesize(getFileSize(apkInfo.getFileurl()));


                        Log.d(TAG, "apk: " + apkInfo);
                        LocalInfo localInfo = getLocalInfo(mContext);
                        if (localInfo.getVersioncode() < apkInfo.getVersioncode()){
                            // Toast.makeText(mContext, "可以更新", Toast.LENGTH_SHORT).show();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mCallback.update(apkInfo);
                                }
                            });

                        }else{
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mCallback.lastest();
                                }
                            });

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(TAG, "eroor: " + e.toString());
                    }
                }
            }
        }).start();
    }


    /**
     * 获取本地版本
     * @param context
     * @return
     */
    private LocalInfo getLocalInfo(Context context){
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            LocalInfo localInfo = new LocalInfo();
            localInfo.setVersioncode(packageInfo.versionCode);
            localInfo.setVersionname(packageInfo.versionName);
            return localInfo;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public void Destroy(){
        mContext.unregisterReceiver(NetUpdateReceiver);
    }
}
